package com.csun.cmny.provider.resolver;

import com.csun.cmny.util.RedisKeyUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Locale;
import java.util.Objects;

/**
 * @Auther: chisj chisj@foxmal.com
 * @Date: 2019-01-18 11:59
 * @Description: the cmny message source
 */
@Slf4j
@Component
public class CmnyMessageSource {

    @Resource
    private MessageSource messageSource;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    private CmnyLocaleResolver cmnyLocaleResolver;

    public String getMessage(String code, Object[] param) {
        Locale locale = LocaleContextHolder.getLocale();
        log.info("local = {}", locale.toString());
        return messageSource.getMessage(code, param, LocaleContextHolder.getLocale());
    }

    /**
     * get code message by group id
     *
     * @param code      the code
     * @param params    the params
     * @param groupId   the group id
     *
     * @return  the code message
     */
    public String getMessage(String code, Object[] params, Long groupId) {

        String language = (String) redisTemplate.opsForValue().get(RedisKeyUtil.getUacGroupLanguageId(groupId));

        Locale locale = Objects.nonNull(language) ? new Locale(language) : Locale.getDefault();

        try {
            return messageSource.getMessage(code, params, locale);
        } catch (Exception e) {
            log.error("===> 需要配置本地化消息 code = {}", code);
            return null;
        }

    }

}
